package com.example.huangliting.experimentalarrangementsystem.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.huangliting.experimentalarrangementsystem.R;
import com.example.huangliting.experimentalarrangementsystem.util.HttpUtils;
import com.example.huangliting.experimentalarrangementsystem.util.MD5Utils;
import com.example.huangliting.experimentalarrangementsystem.util.Utils;
import com.example.huangliting.experimentalarrangementsystem.widget.ItemGroup;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class PersonalMsgModifyAct extends AppCompatActivity implements ItemGroup.ItemOnClickListener{

    private ItemGroup userIdIG, userNameIG, phoneIG, professinalTitleIG,ModifyPasswordUrlIG;
    private String getPersonDataUrl = HttpUtils.headerUrl+"teacher/getPersonalMsg";
    private String updatePersonDataUrl = HttpUtils.headerUrl+"teacher/updatePersonData";
    private Context mContext;
    private Button backBtn;
    private Button update_btn;
    private SharedPreferences sp;
    private JSONObject personalMsgJson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.personalmsg_modify);
        mContext = this;
        sp = this.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        userIdIG = findViewById(R.id.show_userId_ig);
        userNameIG = findViewById(R.id.userName_ig);
        phoneIG = findViewById(R.id.id_phone_ig);
        professinalTitleIG = findViewById(R.id.professinalTitle_ig);
        ModifyPasswordUrlIG = findViewById(R.id.modify_password_url);
        ModifyPasswordUrlIG.setItemOnClickListener(this);

        if (sp.getBoolean("ischeck",false)){
            Map<String, String> params = new HashMap<String, String>();
            params.put("userId",sp.getString("userId",""));
            getPersonData(params, "utf-8");
        }
        //initView();
        userIdIG.setText(sp.getString("userId",""));
        /*返回操作*/
        backBtn = findViewById(R.id.toolbar_left_btn);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                finish();
            }
        });

        update_btn = findViewById(R.id.update_btn);
        update_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                String userId = userIdIG.getText().toString();
                String userName = userNameIG.getText().toString();
                String phoneStr = phoneIG.getText().toString();
                String professinalTitle = professinalTitleIG.getText().toString();
                if (userName==null || userName.equals("")){
                    Toast.makeText(mContext, "未填写姓名", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (userId==null || userId.equals("")){
                    Toast.makeText(mContext, "账号不存在", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (phoneStr==null || phoneStr.equals("")){
                    Toast.makeText(mContext, "未填写联系方式", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (professinalTitle==null || professinalTitle.equals("")){
                    Toast.makeText(mContext, "未填写职称", Toast.LENGTH_SHORT).show();
                    return;
                }

                Map<String, String> params = new HashMap<String, String>();
                params.put("userId",userId);
                params.put("userName", userName);
                params.put("phone", phoneStr);
                params.put("professinalTitle", professinalTitle);
                updatePersonData(params, "utf-8");
                finish();
            }
        });
    }

    @Override
    public void onItemClick(View v) {
        switch (v.getId()) {
            case R.id.modify_password_url:
                Intent i = new Intent(mContext, ModifyPasswordActicvity.class);
                startActivity(i);
                break;
        }
    }

    Handler getPersonalMsgHandler = new Handler() {

        @SuppressLint("WrongConstant")
        public void handleMessage(android.os.Message msg) {
            try {
                JSONObject jsonObj = new JSONObject((String) msg.obj);
                personalMsgJson = jsonObj.getJSONObject("personalMsg");
                if (personalMsgJson!=null){
                    userNameIG.setText(personalMsgJson.getString("tname"));
                    professinalTitleIG.setText(personalMsgJson.getString("professinalTitle"));
                    phoneIG.setText(personalMsgJson.getString("contactWay"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    /*
    * 获取个人资料
    */
    private void getPersonData(final Map<String, String> params, final String encode) {
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    URL url = new URL(getPersonDataUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);

                    //拼接出要提交的数据的字符串
                    byte[] data = HttpUtils.getRequestData(params, encode).toString().getBytes();

                    //添加post请求的两行属性
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-Length", String.valueOf(data.length));

                    //设置打开输出流
                    conn.setDoOutput(true);
                    //拿到输出流
                    OutputStream os = conn.getOutputStream();
                    //使用输出流往服务器提交数据
                    os.write(data);
                    if (conn.getResponseCode() == 200) {
                        InputStream is = conn.getInputStream();
                        String text = Utils.getTextFromStream(is);
                        Message msg = getPersonalMsgHandler.obtainMessage();
                        msg.obj = text;
                        getPersonalMsgHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }

    /*
     * 更新个人资料
     */
    Handler updatePersonalMsgHandler = new Handler() {

        @SuppressLint("WrongConstant")
        public void handleMessage(android.os.Message msg) {
            try {
                JSONObject jsonObj = new JSONObject((String) msg.obj);
                Boolean isSuccess = jsonObj.getBoolean("isSuccess");
                if(isSuccess){
                    Toast.makeText(mContext, "更新成功", Toast.LENGTH_SHORT).show();
                    finish();
                }else
                    Toast.makeText(mContext, "更新失败", Toast.LENGTH_SHORT).show();

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    private void updatePersonData(final Map<String, String> params, final String encode) {
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    URL url = new URL(updatePersonDataUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);

                    //拼接出要提交的数据的字符串
                    byte[] data = HttpUtils.getRequestData(params, encode).toString().getBytes();

                    //添加post请求的两行属性
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-Length", String.valueOf(data.length));

                    //设置打开输出流
                    conn.setDoOutput(true);
                    //拿到输出流
                    OutputStream os = conn.getOutputStream();
                    //使用输出流往服务器提交数据
                    os.write(data);
                    if (conn.getResponseCode() == 200) {
                        InputStream is = conn.getInputStream();
                        String text = Utils.getTextFromStream(is);
                        Message msg = updatePersonalMsgHandler.obtainMessage();
                        msg.obj = text;
                        updatePersonalMsgHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }

}
